package com.siblings.loan.ui.loan.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.lib.base.utils.DensityUtils
import com.lib.base.utils.log.LogHelper
import com.siblings.loan.R
import com.siblings.loan.utils.helper.TestAnalysisAddEvent
import com.siblings.loan.databinding.ActLoanApplyBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.loan.adapter.SibLoanApplyDaysAdapter
import com.siblings.loan.ui.loan.adapter.SibLoanApplyDetailsAdapter
import com.siblings.loan.ui.loan.impl.SibLoanApplyPresenterImpl
import com.siblings.loan.ui.loan.view.ISibLoanApplyView
import com.siblings.loan.utils.decoration.GridSpacingItemDecoration
import com.siblings.loan.utils.dialog.KefuDialog
import com.siblings.loan.utils.event.SibEventData
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.weight.ScaleRulerView.OnValueChangeListener
import com.siblings.mvp.MvpAct
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.math.BigDecimal

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/15 16:42
 * @Annotation：贷款申请
 */
class SibLoanApplyAct: MvpAct<ISibLoanApplyView,SibLoanApplyPresenterImpl>(),ISibLoanApplyView {
    private lateinit var binding: ActLoanApplyBinding

    //选择时间
    private var daysAdapter: SibLoanApplyDaysAdapter? = null
    //明细列表
    private var detailsAdapter: SibLoanApplyDetailsAdapter? = null

    //是否点击申请贷款，只有主动点击申请按钮才会处理总流程刷新通知
    private var isApplyClick = false

    companion object {
        private const val INTENT_KEY_AMOUNT = "defaultAmount"
        fun start(context: Context, amount: String) {
            val intent = Intent(context, SibLoanApplyAct::class.java)
            intent.putExtra(INTENT_KEY_AMOUNT, amount)
            context.startActivity(intent)
        }
    }
    override fun getSibRootView(): View {
        binding = ActLoanApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createMvpPresenter(): SibLoanApplyPresenterImpl {
        return SibLoanApplyPresenterImpl(this)
    }

    override fun initSibView() {
        setSibTitleBarVisibility(View.VISIBLE)
        setSibTitleBarColor(Color.parseColor("#FFF9F9F9"))
        setSibTextTitle(getString(R.string.loan_apply_title))
        setSibBackBtnRes(R.mipmap.pic_back_theme)
        setSibRightBtnRes(R.mipmap.pic_kefu_theme)

        initSibRefreshLayout()
        initSibDaysRecyclerView()
        initSibDetailsRecyclerView()
        EventBus.getDefault().register(this)

        binding.textAmount.text = intent.extras!!.getString(INTENT_KEY_AMOUNT)
        binding.rulerView.setParam(
            DensityUtils.dp2px(10f), DensityUtils.dp2px(17f), DensityUtils.dp2px(17f),
            DensityUtils.dp2px(10f), DensityUtils.dp2px(9f), DensityUtils.dp2px(12f)
        )

        //默认不显示可选额度
        showSibNotOptionalViews()
    }

    override fun initSibListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            showSibKefuDialog("LoanApply Page")
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_CUSTOMER,"LoanApply Page")
        }
        //提交申请
        binding.btnSubmit.setOnClickListener {
            // TODO: 贷款包需要走以下流程
//            isApplyClick = true
//            /**
//             * 流程
//             * 1、需要先通过流程接口，判断订单状态和申请状态
//             * 2、创建贷款申请订单
//             * 3、创建贷款申请订单成功后再验证总流程，返回首页显示审核状态
//             */
//            showSibLoading(isTOuchOut = false, isCancel = true)
//            //发送更新总流程通知
//            EventBus.getDefault().post(SibEventData(SibEventData.TYPE.SIB_PROCESS_REFRESH))
//            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_LOAN_APPLY_CONFIRM,"")

            // TODO: 循环额度不需要验证状态，直接调创建订单接口
            showSibLoading(isTOuchOut = false, isCancel = true)
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_LOAN_APPLY_CONFIRM,"")
            mvpPresenter.onSibCreateApplyOrderAction()
        }
    }

    override fun initSibData() {
        showSibLoading()
        mvpPresenter.loadSibApplyDataAction()
    }

    /* 初始化刷新 */
    private fun initSibRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            mvpPresenter.loadSibApplyDataAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 选择days列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initSibDaysRecyclerView(){
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(9f)
        binding.recyclerView.addItemDecoration(GridSpacingItemDecoration(3,decoration,false))
        val layoutManager = GridLayoutManager(getContext(),3)
        binding.recyclerView.layoutManager = layoutManager
        daysAdapter = SibLoanApplyDaysAdapter(binding.recyclerView)
        daysAdapter!!.setOnItemChildClickListener { _, _, position ->
            val item = this.daysAdapter!!.getItem(position)
            if (item.optBoolean("isSelect",false)){
                return@setOnItemChildClickListener
            }
            for (i in 0..<daysAdapter!!.itemCount){
                val model = daysAdapter!!.getItem(i)
                model.put("isSelect",false)
                if (i == position){
                    model.put("isSelect",true)
                }
            }
            daysAdapter!!.notifyDataSetChanged()

            mvpPresenter.loadSibApplyDataAction()
        }
        binding.recyclerView.adapter = daysAdapter
    }

    /**
     * 初始化明细列表
     */
    private fun initSibDetailsRecyclerView() {
        binding.rvDetails.setHasFixedSize(true)
        binding.rvDetails.isNestedScrollingEnabled = false
        binding.rvDetails.isFocusableInTouchMode = false //不需要焦点
        binding.rvDetails.layoutManager = LinearLayoutManager(this)
        detailsAdapter = SibLoanApplyDetailsAdapter(binding.rvDetails)
        binding.rvDetails.adapter = detailsAdapter!!
        binding.rvDetails.itemAnimator = DefaultItemAnimator()
        detailsAdapter!!.setOnItemChildClickListener{ _, childView, _ ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        }
    }

    /**
     * 获取申请贷款金额
     */
    override fun getSibApplyAmount(): String {
        return binding.textAmount.text.toString()
    }

    /**
     * 获取申请贷款期限
     */
    override fun getSibApplyDays(): String {
        var days = ""
        if (daysAdapter!!.itemCount > 0){
            for (i in 0..<daysAdapter!!.itemCount){
                val item = daysAdapter!!.getItem(i)
                if (item.optBoolean("isSelect",false)){
                    days = item.optString("day")
                    break
                }
            }
        }
        return days
    }

    /**
     * 显示不可选贷款额度
     */
    override fun showSibNotOptionalViews() {
        binding.rulerLayout.visibility = View.GONE
        binding.amountLayout.visibility = View.GONE
    }

    /**
     * 显示可选贷款额度
     */
    override fun showSibOptionalViews(data: JSONObject) {
        binding.rulerLayout.visibility = View.VISIBLE
        binding.amountLayout.visibility = View.VISIBLE

        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        val minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString()
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        //颗粒度
        val granularity = data.optInt("granularity")

        binding.textMinAmount.text = minAmount
        binding.textMaxAmount.text = maxAmount

//        binding.rulerView.setParam(
//            DensityUtils.dp2px(10f), DensityUtils.dp2px(17f), DensityUtils.dp2px(17f),
//            DensityUtils.dp2px(10f), DensityUtils.dp2px(9f), DensityUtils.dp2px(12f)
//        )
        if (minAmount >= maxAmount){
            binding.rulerView.initViewParam(maxAmount.toFloat(), 0f, maxAmount.toFloat() * 100, 10 * granularity)
        } else {
            binding.rulerView.initViewParam(amount.toFloat(), minAmount.toFloat(), maxAmount.toFloat(), 10 * granularity)
        }
        binding.rulerView.setValueChangeListener(object : OnValueChangeListener{
            override fun onValueChange(value: Float) {
                var showValue = value
                if (minAmount >= maxAmount){
                    showValue = maxAmount.toFloat()
                }
                binding.textAmount.text ="${showValue.toInt()}"
            }
            override fun onValueComplete(value: Float) {
                mvpPresenter.loadSibApplyDataAction()
            }
        })
    }

    /**
     * 设置贷款期限
     */
    override fun showSibLoanDurationList(data: JSONObject) {
        if (daysAdapter!!.itemCount == 0){
            //默认天数
            val defaultDays = data.optString("days")
            val daysArray = data.optJSONArray("daysArray")
            val dayList = arrayListOf<JSONObject>()
            if (daysArray != null) {
                //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                var isNeedAdd = true
                for (i in 0..<daysArray.length()){
                    if (daysArray.optString(i) == defaultDays){
                        isNeedAdd = false
                        break
                    }
                }
                if (isNeedAdd){
                    daysArray.put(0,defaultDays)
                }

                for (i in 0..<daysArray.length()){
                    val day = daysArray.optString(i)
                    val obj = JSONObject()
                    obj.put("day",day)
                    obj.put("isSelect",day == defaultDays)
                    dayList.add(obj)
                }
            }
            daysAdapter!!.data = dayList
        }
    }

    /**
     * 设置贷款明细
     */
    override fun showSibLoadDetailsList(data: JSONObject) {
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        binding.textAmount.text = amount

        //明细
        val array = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                dataList.add(array.optJSONObject(i))
            }
        }
        detailsAdapter!!.data = dataList
    }

    /**
     * 贷款申请成功
     */
    override fun showSibLoanApplySuccess() {
        //注销事件监听
        EventBus.getDefault().unregister(this)
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        //发送更新总流程通知
        EventBus.getDefault().post(SibEventData(SibEventData.TYPE.SIB_PROCESS_REFRESH))
        //进入SMS信息收集预览页面
        SibLoanApplyWaitAct.start(this,getSibApplyAmount(),getSibApplyDays())
        Handler(Looper.myLooper()!!).postDelayed({
           finish()
        },500)
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showSibLoanApplyFailed() {
        hideSibLoading()
        finish()
    }

    /**
     * 进入申请贷款等待页面
     */
    override fun showSibLoanApplyWaitPage() {
        SibLoanApplyWaitAct.start(this,getSibApplyAmount(),getSibApplyDays())
    }

    /**
     * 显示客服dialog
     */
    private fun showSibKefuDialog(eventRemark: String){
        val kefuDialog = KefuDialog(this,eventRemark,object : KefuDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        kefuDialog.setCancelable(true)
        kefuDialog.setCanceledOnTouchOutside(true)
        kefuDialog.show()
    }

    /**
     * 更新总流程完成
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun onRefreshProcessCompleted(event: SibEventData){
        LogHelper.e("process refresh success >>>>>>>>>>")
        if (event.eventType == SibEventData.TYPE.SIB_PROCESS_REFRESHED){
            if (isApplyClick){
                mvpPresenter.onSibCheckProcessAction()
                isApplyClick = false
            }
        }
    }

    override fun hideSibLoading() {
        super.hideSibLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_LOAN_APPLY_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_LOAN_APPLY_END,"")
        EventBus.getDefault().unregister(this)
    }
}